﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Net;
using System.Net.Sockets;
using System.IO;


namespace testProtobuf.Network
{
    class TcpConnection
    {
        IPAddress _ip = null;
        int _port = 0;
        Socket _socket = null;
        bool _bIsInitialized = false;
       

        public bool Create(String ip, int port, int bufSize = 1024, bool isblocking = false)
        {
            if (_bIsInitialized)
            {
                Console.WriteLine("TcpConnection Already Initialized!!!");
                return false;
            }
            
            try
            {
                _ip = IPAddress.Parse(ip);
                _port = port;
                
                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _socket.Connect(new IPEndPoint(_ip, _port));
                _socket.Blocking = isblocking;

                _bIsInitialized = true;
                return true;
            }
            catch (System.Exception e)
            {
                _bIsInitialized = false;
                Console.WriteLine("Tcp Create Error" + e.Message);
            }

            return false;
        }

        public void Destroy()
        {
            if (_bIsInitialized)
            {
                if (_socket != null)
                {
                    _socket.Disconnect(true);
                    _socket.Shutdown(SocketShutdown.Both);
                    _socket.Close();
                    _socket = null;
                    _bIsInitialized = false;
                }
            }

        }

        public bool IsConnected()
        {
            return false;
        }

        public bool SendMessage(byte[] message, int length)
        {
            if (!_bIsInitialized)
                return false;

            try
            {
                int result = _socket.Send(message, length, 0);
                if (result != 0)
                    return true;
            }
            catch (System.Exception e)
            {
                Console.WriteLine("Tcp SendMessage Error " + e.Message);
            }
            return false;
        }


        public int ReceiveMessage(ref byte[] receiveBytes, int streamLength)
        {
            int lengh = _socket.Receive(receiveBytes, streamLength, 0);
            return lengh;
        }
    }
}
